#include "selectfilewizardpage.h"
#include "ui_selectfilewizardpage.h"

#include "setting.h"

#include <QFileDialog>
#include <QList>
#include <QStringList>
#include <QFileInfo>

SelectFileWizardPage::SelectFileWizardPage(QWidget *parent) :
    QWizardPage(parent),
    ui(new Ui::SelectFileWizardPage)
{
    ui->setupUi(this);

    registerField(tr("已选择的文件*"),ui->fileList);
}

SelectFileWizardPage::~SelectFileWizardPage()
{
    delete ui;
}

void SelectFileWizardPage::on_btnAdd_clicked()
{
    QStringList files;

    files = QFileDialog::getOpenFileNames(this,
	 tr("选择要转换的影音文件"),
	 global_settings.value(SETTING_SELECTFILEWIZARD_LASTDIR,"").toString()
					  );

    if (files.count()) {
	QFileInfo info (files.at(0));
	global_settings.setValue(SETTING_SELECTFILEWIZARD_LASTDIR,
				 info.dir().path());
    }

    ui->fileList->addItems(files);
    decideBtnsEnable();

}




void SelectFileWizardPage::decideBtnsEnable() {
    if (ui->fileList->currentItem() == NULL ||
	!ui->fileList->count()) {
	// Nothing left in the list or nothing selected
	ui->btnDelete->setEnabled(false);
	ui->btnUp->setEnabled(false);
	ui->btnDown->setEnabled(false);
	return;
    }

    ui->btnUp->setEnabled(
	    (ui->fileList->currentRow() > 0) &&
	    (ui->fileList->count() > 1)
	    );

    ui->btnDown->setEnabled(
	    (ui->fileList->currentRow() < ui->fileList->count() - 1) &&
	    (ui->fileList->count() > 1)
	    );

    ui->btnDelete->setEnabled(
	    ui->fileList->currentItem() != NULL
	    );
}

void SelectFileWizardPage::on_fileList_currentItemChanged(QListWidgetItem* , QListWidgetItem* )
{
    decideBtnsEnable();
}



void SelectFileWizardPage::on_btnUp_clicked()
{
    if (ui->fileList->currentRow() <= 0 ||
	!ui->fileList->count()) {
	ui->btnUp->setEnabled(false);
	return;
    }

    int row = ui->fileList->currentRow();

    QListWidgetItem *item = ui->fileList->takeItem(row);
    ui->fileList->insertItem(row-1,item);
    ui->fileList->setCurrentItem(item);
}

void SelectFileWizardPage::on_btnDown_clicked()
{
    if (ui->fileList->currentRow() >= ui->fileList->count() - 1 ||
	!ui->fileList->count()) {
	ui->btnDown->setEnabled(false);
	return;
    }

    int row = ui->fileList->currentRow();

    QListWidgetItem *item = ui->fileList->takeItem(row);
    ui->fileList->insertItem(row+1,item);
    ui->fileList->setCurrentItem(item);
}

void SelectFileWizardPage::on_btnDelete_clicked()
{
    if (!ui->fileList->count()) {
	ui->btnDelete->setEnabled(false);
	return;
    }

    int row = ui->fileList->currentRow();
    QListWidgetItem *item = ui->fileList->takeItem(row);
    delete item;
    decideBtnsEnable();
}
